﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wedo.Mvc.Utility;
using Wedo.Recognition.Domain.Models;
using System.IO;
using Wedo.Recognition.Web.Controllers;
using Wedo.Service.Common;
using Wedo.Recognition.Service;
using Wedo.Mvc.Pager;
using Wedo.Domain.Models;
using System.Data.Entity.Infrastructure;
using Wedo.Recognition.Domain; 
using Wedo.Recognition.Repository;

namespace Wedo.IPRP.Web.Controllers
{
    public class ReleaseOrderController : EntityController<ReleaseOrder, ReleaseOrderSearch>
    {
        private BankDataService dbService;
        private BaseService<ReleaseOrder> service;
        public ReleaseOrderController(IUnitWork dbContext)
            : base(dbContext)
        {
            service = new BaseService<ReleaseOrder>(_dbContext, _dbContext.Set<ReleaseOrder>());
            dbService = new BankDataService(_dbContext);
        }
        #region finace

        /// <summary>
        /// 需要我处理的放单
        /// </summary>
        /// <returns></returns>
        public ActionResult MyWaitedOrder()
        {
            var where = new ReleaseOrderSearch { Status = (int)ApprovalStatus.Waited, Approver = CurrentUserName };
            ViewData["SearchModel"] = where;
            var list = GetSearchPagedList(where);
            return ReturnAjaxView("Index", list);

        }

        public override ActionResult Index()
        {
            return Search(new ReleaseOrderSearch { Approver=CurrentUserName});
        }

        /// <summary>
        /// 财务同意放单
        /// </summary>
        [HttpPost]
        public JsonResult ConfirmOrder(Guid id)
        {
            ResultMSG res = new ResultMSG();
             try
            {
                dbService.ConfirmOrder(id, this.User.Identity.Name);
                res.Result =true;
                res.MSG = Wedo.Recognition.Resources.ErrorMessage.Finance_To_Confirm;
            }
            catch (Exception ex)
            {
                res.Result =false;
                res.MSG = ex.Message;
            }
            return Json(res);
        }

        /// <summary>
        /// 批量财务同意放单
        /// </summary>
        [HttpPost]
        public JsonResult ConfirmOrders(FormCollection forms)
        {
            if (string.IsNullOrEmpty(forms["ids"]))
            {
                return ErrorMSG("请至少选择一个！");
            }
            else
            {
                var ids = forms["ids"].Split(',')
                    .Where(m => m.TryParseTo<Guid>().HasValue)
                    .Select(m => m.TryParseTo<Guid>().Value).ToList();
                ResultMSG res = new ResultMSG();
                 try
                {
                    dbService.ConfirmOrders(ids, CurrentUserName);

                    return SuccessMsg(Wedo.Recognition.Resources.ErrorMessage.Finance_To_Confirm);
                }
                catch (Exception ex)
                {
                    return ErrorMSG(ex.Message);
                }
             }
        }

        /// <summary>
        /// 批量财务同意放单
        /// </summary>
        /// 
        [HttpPost]
        public JsonResult RejectOrders(FormCollection forms)
        {
            if (string.IsNullOrEmpty(forms["ids"]))
            {
                return ErrorMSG("请至少选择一个！");
            }
            else
            {
                var ids = forms["ids"].Split(',')
                    .Where(m => m.TryParseTo<Guid>().HasValue)
                    .Select(m => m.TryParseTo<Guid>().Value).ToList();
                ResultMSG res = new ResultMSG();
                 try
                {
                    dbService.RejectOrders(ids, CurrentUserName);

                    return SuccessMsg(Wedo.Recognition.Resources.ErrorMessage.Finance_To_Cancel);
                }
                catch (Exception ex)
                {
                    return ErrorMSG(ex.Message);
                }
            }
        }

        /// <summary>
        /// 财务拒绝放单
        /// </summary>
        [HttpPost]
        public JsonResult RejectOrder(Guid id)
        {
            ResultMSG res = new ResultMSG();
             try
            {
                dbService.RejectOrder(id, this.User.Identity.Name);
                res.Result =true;
                res.MSG = Wedo.Recognition.Resources.ErrorMessage.Finance_To_Cancel;
            }
            catch (Exception ex)
            {
                res.Result =false;
                res.MSG = ex.Message;
            }
            return Json(res);
        }
        #endregion

        #region csr
        public ActionResult MyIndex()
        {
            var where = new ReleaseOrderSearch { ApplyMan = CurrentUserName };
            var list = GetSearchPagedList(where);
            
            ViewData["SearchModel"] = where;

            return ReturnAjaxView("Index", list);
        }
        #endregion

        protected override IBaseService<ReleaseOrder> EntityService
        {
            get { return service; }
        }

        protected override ReleaseOrder FindById(Guid Id)
        {
            return service.GetAll(m => m.Id == Id, "BankData").FirstOrDefault();
        }

        protected override PagedList<ReleaseOrder> GetSearchPagedList(ReleaseOrderSearch where)
        {
            //SetUserInfo();

            where = where ?? new ReleaseOrderSearch();

            var query = service.GetAll(includes: "BankData");
            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.ApplyTime > Start);
            }
            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.ApplyTime < endTime);
            }

            if (where.Status != null)
                query = query.Where(m => m.Status == where.Status);

            //处理人
            if (where.Approver.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.Approver == where.Approver);
            }

            //申请人
            if (where.ApplyMan.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.ApplyMan == where.ApplyMan);
            }
            if (where.Keyword.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.BankData.Assiginment.Contains(where.Keyword));
            }

            var list= query .OrderBy(m => m.Status).ThenByDescending(m => m.Created).ToPagedList(where.Page, 10);
 
            return list;
        }
    }
}
